package com.tanhua.api;

import cn.hutool.core.util.ObjectUtil;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.sso.pojo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class FriendServiceApiImpi implements FriendServiceApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    //判断是否是好友
    @Override
    public boolean selectFriend(Long nowId, Long friendId) {
        Criteria criteria = Criteria.where("userId").is(nowId).and("friendId").is(friendId);
        boolean exists = mongoTemplate.exists(Query.query(criteria), Friend.class);
        return exists;
    }

    //添加好友
    @Override
    public void addFriend(Friend friend) {
        mongoTemplate.save(friend);
    }

    @Override
    public List<Long> myFriendIds(Long nowId) {
        Criteria criteria = Criteria.where("userId").is(nowId);
        List<Friend> friends = mongoTemplate.find(Query.query(criteria).with(Sort.by(Sort.Order.desc("created"))), Friend.class);
        List<Long> list = friends.stream().map(Friend::getFriendId).collect(Collectors.toList());
        return list;
    }

    //解除好友关系
    @Override
    public void deleteFriend(Long userId, Long likeUserId) {
        Criteria criteria = Criteria.where("userId").is(userId).and("friendId").is(likeUserId);
        DeleteResult remove = mongoTemplate.remove(Query.query(criteria), Friend.class);
        Criteria criteria1 = Criteria.where("userId").is(likeUserId).and("friendId").is(userId);
        DeleteResult remove1 = mongoTemplate.remove(Query.query(criteria1), Friend.class);
    }
}
